import hashlib
import json
import re
from django.shortcuts import redirect
from sortUrlBackEnd import settings
import requests
from django.http import JsonResponse
from sorturl import Mysql


def Index(requests):
    return redirect("https://www.kratos.fun")


def Sort(requests):
    data = {
        "status": False,
        "msg": "",
        "sorturl": ""
    }
    if requests.method == "POST":
        postdata = json.loads(str(requests.body, encoding='utf-8'))
        print(postdata)
        if postdata["url"]:
            # 判断是哪一种post
            # 第一个为生成短链接
            if postdata["option"] == "1":
                if len(postdata["url"]) < 500:
                    status, msg = getsort(postdata["url"])
                    if status:
                        data["msg"] = "转换失败，链接重复" + str(status) + "次"
                        print(data["msg"])
                    else:
                        data["status"] = True
                        data["msg"] = "转换成功，请点击复制"
                        data["sorturl"] = "https://" + settings.sortUrl + "/" + msg
                else:
                    data["msg"] = "宁这链接也太长了，自己背下来就好了"
            elif postdata["option"] == "2":
                if len(postdata["url"]) < 50:
                    status, res = get_real_url(postdata["url"])
                    if status:
                        data["status"] = True
                        data["msg"] = "查询成功，请点击复制"
                        data["sorturl"] = res
                    else:
                        data["msg"] = res
                else:
                    data["msg"] = str(len(postdata["url"])) + "个字节，你管这叫短链接？"
            else:
                data["msg"] = "其他功能再考虑考虑吧"
        else:
            data["msg"] = "请真的输入链接"
    else:
        data["msg"] = "你真的要get吗？"
    return JsonResponse(data)


def getsort(tmpfullurl, initcount=0, fullurl=""):
    if not fullurl:
        fullurl = tmpfullurl
    same_hash_count = 0
    # 先判断是否已生成同一个链接
    sql = "SELECT * FROM `urls` WHERE `fullurl`='%s'" % fullurl
    res = Mysql.MysqlPool(sql, 1)
    if res:
        return 0, res["hashurl"]
    hashlist, hash_md5 = full2sort(tmpfullurl)
    for sorturl in hashlist:
        sql = "SELECT * FROM `urls` WHERE `hashurl`='%s'" % sorturl
        res = Mysql.MysqlPool(sql, 1)
        if not res:
            sql = "INSERT INTO `sorturl`.`urls`(`hashurl`, `fullurl`, `creattime`) VALUES ('%s', '%s', NOW());" % (
                sorturl, fullurl)
            Mysql.MysqlPool(sql, 0)
            return 0, sorturl
        same_hash_count += 1
    if not initcount:
        tmpcount, tmpstr = getsort(hash_md5, same_hash_count, fullurl)
        same_hash_count += tmpcount
    return same_hash_count, "短url已多次重复，请联系开发者"


def full2sort(fullurl):
    hash_md5 = hashlib.md5(fullurl.encode('utf-8')).hexdigest()
    return [hash_md5[0:8], hash_md5[8:16], hash_md5[16:24], hash_md5[24:32]], hash_md5


def get_real_url(url):
    domain = re.findall("http.?://(.*?)/(.*)", url)
    if domain and domain[0][0] in settings.ALLOWED_HOSTS:
        sql = "SELECT * FROM `urls` WHERE `hashurl`='%s'" % domain[0][1]
        res = Mysql.MysqlPool(sql, 1)
        if res:
            return True, res["fullurl"]
        else:
            return False, "未查询到该短链接：" + domain[0][1]
    else:
        return get_other_real_url(url)


def get_other_real_url(url):
    try:
        res = requests.get(url, timeout=5).url
        return True, res
    except requests.exceptions.ReadTimeout as e:
        res = "链接解析超时:" + str(e)
    except requests.exceptions.ConnectionError as e:
        res = "链接解析失败:" + str(e)
    except Exception as e:
        print(type(e), e)
        res = str(type(e)) + ":" + str(e)
    return False, res


def GetUrl(requests, hash_md5):
    hash_md5 = ''.join(filter(str.isalnum, hash_md5))
    print(hash_md5)
    if len(hash_md5) == 8:
        sql = "SELECT * FROM `urls` WHERE `hashurl`='%s'" % hash_md5
        res = Mysql.MysqlPool(sql, 1)
        if res:
            print(res["fullurl"])
            return redirect(res["fullurl"])
    return redirect("http://" + settings.sortUrl)
